#! /usr/bin/env python
#coding=utf-8

import os
import codecs

class MachSystemVmStat(dict):
    def __init__(self, filename):
        super().__init__()
        self.__load(filename)

    def __parse_one_line(self, line):
        parts = line.split(":")
        val = parts[1].strip()
        if val.endswith("."):
            val = val[:-1]
        try:
            val = int(val)
        except:
            return
        name = parts[0].replace('"', "").strip()
        name = name.replace(" ", "_")
        name = name.replace("-", "_")
        self[name] = val

    def __load(self, filename):
        with codecs.open(filename, 'r', 'utf-8') as f:
            for line in f.readlines():
                line = line.strip()
                self.__parse_one_line(line)

    def report(self, fileName):
        f = open(fileName, "w")
        f.write("<vm_stat>\n")
        for k in self.keys():
            f.write("<%s>%s</%s>\n" % (k, self[k], k))
        f.write("</vm_stat>\n")
        f.close()

if __name__ == "__main__":
    import sys
    import traceback

    if len(sys.argv) <= 1:
        print("vm_stat.py vm_stat_file_name")
        sys.exit()

    footprint = sys.argv[1]
    try:
        print("Parsing vm_stat file: %s" % footprint)
        p = MachSystemVmStat(footprint)
        print(p)
        out = os.path.splitext(footprint)[0] + ".xml"
        p.report(out)
        print("  parsed vm_stat file: %s" % out)
    except:
        traceback.print_exc()
